<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>{{ isEdit ? '编辑医疗记录' : '新增医疗记录' }}</h3>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        label-position="right"
        status-icon
      >
        <el-divider content-position="left">患者信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="患者" prop="patientId">
              <el-select 
                v-model="form.patientId" 
                filterable 
                remote 
                reserve-keyword
                placeholder="请输入患者姓名或ID搜索" 
                :remote-method="searchPatients"
                :loading="patientLoading"
                style="width: 100%"
                @change="handlePatientChange"
              >
                <el-option 
                  v-for="item in patientOptions" 
                  :key="item.id" 
                  :label="`${item.name} (${item.patientId})`"
                  :value="item.id" 
                >
                  <div class="patient-option">
                    <span>{{ item.name }}</span>
                    <span class="patient-id">{{ item.patientId }}</span>
                    <span class="patient-info">{{ item.gender }} {{ item.age }}岁</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="就诊ID" prop="visitId">
              <el-input v-model="form.visitId" placeholder="请输入就诊ID" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="就诊日期" prop="visitDate">
              <el-date-picker 
                v-model="form.visitDate" 
                type="datetime" 
                placeholder="选择就诊日期和时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="科室" prop="departmentId">
              <el-select 
                v-model="form.departmentId" 
                placeholder="请选择科室" 
                filterable
                style="width: 100%"
                @change="handleDepartmentChange"
              >
                <el-option 
                  v-for="item in departmentOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="主诊医生" prop="doctorId">
              <el-select 
                v-model="form.doctorId" 
                placeholder="请选择医生" 
                filterable
                style="width: 100%"
              >
                <el-option 
                  v-for="item in doctorOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="记录状态" prop="status">
              <el-select 
                v-model="form.status" 
                placeholder="请选择状态"
                style="width: 100%"
              >
                <el-option label="草稿" value="草稿" />
                <el-option label="已完成" value="已完成" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">主诉与现病史</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="主诉" prop="chiefComplaint">
              <el-input 
                v-model="form.chiefComplaint" 
                type="textarea" 
                :rows="2" 
                placeholder="请输入患者主诉" 
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="现病史" prop="presentIllness">
              <el-input 
                v-model="form.presentIllness" 
                type="textarea" 
                :rows="3" 
                placeholder="请输入现病史" 
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="既往史" prop="pastHistory">
              <el-input 
                v-model="form.pastHistory" 
                type="textarea" 
                :rows="2" 
                placeholder="请输入既往史" 
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">体格检查</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="血压(mmHg)" prop="physicalExam.bloodPressure">
              <el-input v-model="form.physicalExam.bloodPressure" placeholder="如: 120/80" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="脉搏(次/分)" prop="physicalExam.pulse">
              <el-input v-model="form.physicalExam.pulse" placeholder="如: 75" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="体温(℃)" prop="physicalExam.temperature">
              <el-input v-model="form.physicalExam.temperature" placeholder="如: 36.5" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="体重(kg)" prop="physicalExam.weight">
              <el-input v-model="form.physicalExam.weight" placeholder="如: 65" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="身高(cm)" prop="physicalExam.height">
              <el-input v-model="form.physicalExam.height" placeholder="如: 170" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">诊断与治疗</el-divider>
        
        <el-form-item label="诊断" prop="diagnosis">
          <el-table :data="form.diagnosis" style="width: 100%" border>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  size="small" 
                  circle
                  @click="removeDiagnosis(scope.$index)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="诊断类型" width="150">
              <template #default="scope">
                <el-select v-model="scope.row.type" placeholder="请选择类型" style="width: 100%">
                  <el-option label="初步诊断" value="初步诊断" />
                  <el-option label="确诊" value="确诊" />
                  <el-option label="待排除" value="待排除" />
                  <el-option label="鉴别诊断" value="鉴别诊断" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="诊断编码" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.code" placeholder="诊断编码"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="诊断名称">
              <template #default="scope">
                <el-input v-model="scope.row.name" placeholder="请输入诊断名称"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="诊断描述">
              <template #default="scope">
                <el-input v-model="scope.row.description" placeholder="请输入诊断描述"></el-input>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px;">
            <el-button type="primary" @click="addDiagnosis">添加诊断</el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="治疗计划" prop="treatmentPlan">
          <el-input 
            v-model="form.treatmentPlan" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入治疗计划" 
          />
        </el-form-item>
        
        <el-divider content-position="left">多媒体资料</el-divider>
        
        <el-form-item label="多媒体资料" prop="multimedia">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="file-tip">请上传相关检查报告、图像等资料，支持图片和PDF格式</div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancelForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { medicalRecordAPI, patientAPI, departmentAPI } from '@/utils/api'
import { getDepartmentOptions, getDoctorOptions, refreshAllData, getDepartmentDoctors } from '@/utils/formData'

// 路由相关
const route = useRoute()
const router = useRouter()
const recordId = computed(() => route.params.id)
const isEdit = computed(() => route.name === 'MedicalRecordEdit')

// 表单引用
const formRef = ref(null)

// 表单数据
const form = reactive({
  patientId: '',
  visitId: '',
  visitDate: new Date(),
  departmentId: '',
  doctorId: '',
  chiefComplaint: '',
  presentIllness: '',
  pastHistory: '',
  physicalExam: {
    bloodPressure: '',
    pulse: '',
    temperature: '',
    weight: '',
    height: ''
  },
  diagnosis: [{ type: '初步诊断', code: '', name: '', description: '' }],
  treatmentPlan: '',
  multimedia: [],
  status: '草稿'
})

// 表单验证规则
const rules = {
  patientId: [{ required: true, message: '请选择患者', trigger: 'change' }],
  visitId: [{ required: true, message: '请输入就诊ID', trigger: 'blur' }],
  visitDate: [{ required: true, message: '请选择就诊日期', trigger: 'change' }],
  departmentId: [{ required: true, message: '请选择科室', trigger: 'change' }],
  doctorId: [{ required: true, message: '请选择医生', trigger: 'change' }],
  chiefComplaint: [{ required: true, message: '请输入患者主诉', trigger: 'blur' }],
  presentIllness: [{ required: true, message: '请输入现病史', trigger: 'blur' }],
  treatmentPlan: [{ required: true, message: '请输入治疗计划', trigger: 'blur' }],
  diagnosis: [{ 
    type: 'array', 
    required: true, 
    message: '请至少添加一个诊断', 
    trigger: 'change',
    validator: (rule, value) => value.length > 0 && value.every(item => !!item.name)
  }],
}

// 科室选项
const departmentOptions = ref([])
// 医生选项
const doctorOptions = ref([])
// 患者选项
const patientOptions = ref([])
// 患者加载状态
const patientLoading = ref(false)

// 文件列表
const fileList = ref([])

// 获取医疗记录详情
const getRecordDetail = async () => {
  try {
    const res = await medicalRecordAPI.getMedicalRecord(recordId.value)
    console.log('获取医疗记录详情成功:', res.data)
    
    // 填充表单数据
    Object.keys(form).forEach(key => {
      if (key in res.data && res.data[key] !== null) {
        if (key === 'physicalExam') {
          form.physicalExam = { ...form.physicalExam, ...res.data.physicalExam }
        } else {
          form[key] = res.data[key]
        }
      }
    })
    
    // 处理多媒体文件
    if (res.data.multimedia && res.data.multimedia.length > 0) {
      form.multimedia = res.data.multimedia
      fileList.value = res.data.multimedia.map(item => ({
        uid: item.fileId,
        name: item.description || '文件',
        url: `/api/v1/files/data/${item.fileId}`,
        status: 'success'
      }))
    }
    
    // 获取相关患者信息
    if (res.data.patientInfo) {
      patientOptions.value = [res.data.patientInfo]
    }
    
    console.log('表单数据填充完成，科室ID:', form.departmentId)
    
    // 确保科室ID存在后，显式加载对应科室的医生
    if (form.departmentId) {
      console.log('编辑模式：加载科室对应的医生列表')
      await handleDepartmentChange(form.departmentId)
    }
  } catch (error) {
    console.error('获取医疗记录详情失败', error)
    ElMessage.error('获取医疗记录详情失败')
  }
}

// 添加诊断
const addDiagnosis = () => {
  form.diagnosis.push({
    type: '初步诊断',
    code: '',
    name: '',
    description: ''
  })
}

// 移除诊断
const removeDiagnosis = (index) => {
  form.diagnosis.splice(index, 1)
}

// 搜索患者
const searchPatients = async (query) => {
  if (query.length < 2) return
  patientLoading.value = true
  try {
    const res = await patientAPI.getPatients({ 
      name: query,
      limit: 10
    })
    patientOptions.value = res.data.patients
  } catch (error) {
    console.error('搜索患者失败', error)
  } finally {
    patientLoading.value = false
  }
}

// 处理患者变化
const handlePatientChange = (patientId) => {
  // 可以在这里获取患者详情并填充相关信息
}

// 获取科室列表
const getDepartments = async () => {
  try {
    console.log('开始获取科室列表')
    
    // 直接从API获取科室列表，不依赖缓存
    const response = await departmentAPI.getAllDepartments()
    console.log('API返回的科室列表原始数据:', response)
    
    if (response.success && response.data) {
      // 转换科室数据为选项格式
      departmentOptions.value = Array.isArray(response.data) 
        ? response.data.map(dept => ({
            value: dept.id,
            label: dept.name,
            ...dept
          }))
        : []
      
      console.log('处理后的科室选项:', departmentOptions.value)
    } else {
      console.warn('API返回的科室列表数据异常，使用默认科室数据')
      
      // 使用默认科室数据
      departmentOptions.value = [
        { value: '1', label: '内科' },
        { value: '2', label: '外科' },
        { value: '3', label: '儿科' },
        { value: '4', label: '妇产科' },
        { value: '5', label: '眼科' },
        { value: '6', label: '口腔科' }
      ]
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
    ElMessage.error('获取科室列表失败，请刷新页面重试')
    
    // 出错时使用默认科室数据
    departmentOptions.value = [
      { value: '1', label: '内科' },
      { value: '2', label: '外科' },
      { value: '3', label: '儿科' },
      { value: '4', label: '妇产科' },
      { value: '5', label: '眼科' },
      { value: '6', label: '口腔科' }
    ]
  }
}

// 处理科室变化
const handleDepartmentChange = async (departmentId) => {
  console.log('科室变更为:', departmentId, '类型:', typeof departmentId)
  
  // 先清空医生选择和选项
  form.doctorId = '' 
  doctorOptions.value = []
  
  if (!departmentId) {
    console.warn('科室ID为空，无法获取医生列表')
    return
  }
  
  try {
    // 直接从API获取科室详情，跳过缓存机制
    console.log('直接从API获取科室详情，科室ID:', departmentId)
    const deptDetail = await departmentAPI.getDepartment(departmentId)
    console.log('科室详情API响应:', deptDetail)
    
    if (deptDetail.success && deptDetail.data) {
      const dept = deptDetail.data
      const deptDoctors = []
      
      // 规范化科室ID
      const normalizedDeptId = dept.id.toString()
      console.log('规范化科室ID:', normalizedDeptId)
      
      // 计算总医生数量（包括科室主任和普通医生）
      const headDoctor = dept.headDoctorInfo ? 1 : 0
      const regularDoctors = dept.doctors && Array.isArray(dept.doctors) ? dept.doctors.length : 0
      const totalDoctors = headDoctor + regularDoctors
      
      // 输出科室详情关键信息，帮助调试
      console.log('科室名称:', dept.name)
      console.log('科室主任:', dept.headDoctorInfo?.name || '无')
      console.log('科室普通医生数量:', regularDoctors)
      console.log('科室总医生数量:', totalDoctors)
      
      // 提取科室主任医生信息
      if (dept.headDoctorInfo) {
        const headDoctor = {
          id: dept.headDoctorInfo.id,
          name: dept.headDoctorInfo.name,
          title: dept.headDoctorInfo.title || '主任医师',
          departmentId: normalizedDeptId,
          departmentName: dept.name,
          staffId: dept.headDoctorInfo.staffId
        }
        deptDoctors.push(headDoctor)
        console.log('添加科室主任:', headDoctor.name)
      }
      
      // 提取科室医生列表
      if (dept.doctors && Array.isArray(dept.doctors) && dept.doctors.length > 0) {
        dept.doctors.forEach(doctor => {
          // 避免重复添加医生（比如科室主任可能也在doctors列表中）
          if (!deptDoctors.find(d => d.id === doctor.id)) {
            const doctorInfo = {
              id: doctor.id,
              name: doctor.name,
              title: doctor.title || '医师',
              departmentId: normalizedDeptId,
              departmentName: dept.name,
              staffId: doctor.staffId,
              specialties: doctor.specialties
            }
            deptDoctors.push(doctorInfo)
            console.log('添加科室医生:', doctorInfo.name)
          } else {
            console.log('跳过重复医生:', doctor.name)
          }
        })
      }
      
      // 如果找到了医生，直接使用
      if (deptDoctors.length > 0) {
        console.log('科室医生添加完成，共', deptDoctors.length, '个医生')
        
        // 转换为选项格式 - 确保显示名称而不是ID
        doctorOptions.value = deptDoctors.map(doctor => ({
          value: doctor.id,
          label: `${doctor.name}（${doctor.title}）`,
          name: doctor.name,
          title: doctor.title,
          departmentId: normalizedDeptId,
          departmentName: dept.name
        }))
        
        console.log('更新医生选项成功，最终医生数量:', doctorOptions.value.length)
        return
      } else {
        console.warn('科室详情中没有找到医生数据，尝试创建默认医生')
      }
    } else {
      console.warn('获取科室详情失败或数据格式不正确')
    }
    
    // 如果API获取失败或没有医生数据，创建默认医生
    console.log('为科室创建默认医生数据')
    
    // 获取科室名称
    let deptName = '未知科室'
    try {
      if (deptDetail.success && deptDetail.data && deptDetail.data.name) {
        deptName = deptDetail.data.name
      } else {
        // 尝试从科室选项中获取名称
        const dept = departmentOptions.value.find(dept => dept.value === departmentId)
        if (dept) {
          deptName = dept.label
        } else {
          // 根据ID判断常见科室
          if (departmentId === '1' || departmentId === 1) {
            deptName = '内科'
          } else if (departmentId === '2' || departmentId === 2) {
            deptName = '外科'
          } else if (departmentId === '3' || departmentId === 3) {
            deptName = '儿科'
          } else if (departmentId === '4' || departmentId === 4) {
            deptName = '妇产科'
          } else if (departmentId === '5' || departmentId === 5) {
            deptName = '眼科'
          } else if (departmentId === '6' || departmentId === 6) {
            deptName = '口腔科'
          }
        }
      }
    } catch (error) {
      console.error('获取科室名称出错:', error)
    }
    
    // 创建默认医生数据
    const defaultDoctors = [
      { 
        id: `${departmentId}-1`, 
        value: `${departmentId}-1`, 
        name: `${deptName}主任[模拟]`, 
        label: `${deptName}主任[模拟]（主任医师）`, 
        title: '主任医师', 
        departmentId,
        departmentName: deptName
      },
      { 
        id: `${departmentId}-2`, 
        value: `${departmentId}-2`, 
        name: `${deptName}副主任[模拟]`, 
        label: `${deptName}副主任[模拟]（副主任医师）`, 
        title: '副主任医师', 
        departmentId,
        departmentName: deptName
      },
      { 
        id: `${departmentId}-3`, 
        value: `${departmentId}-3`, 
        name: `${deptName}医生[模拟]`, 
        label: `${deptName}医生[模拟]（主治医师）`, 
        title: '主治医师', 
        departmentId,
        departmentName: deptName
      }
    ]
    
    doctorOptions.value = defaultDoctors
    console.log('已创建默认医生数据:', doctorOptions.value.length, '个医生')
    
  } catch (error) {
    console.error('获取医生列表失败:', error)
    ElMessage.error('获取医生列表失败，使用默认医生数据')
    
    // 出错时使用最简单的默认医生数据
    doctorOptions.value = [
      { 
        value: `${departmentId}-1`, 
        label: `${departmentId}科主任医师[模拟]`,
        name: `${departmentId}科主任[模拟]`,
        title: '主任医师',
        departmentId,
        departmentName: `科室${departmentId}`
      },
      { 
        value: `${departmentId}-2`, 
        label: `${departmentId}科副主任医师[模拟]`,
        name: `${departmentId}科副主任[模拟]`,
        title: '副主任医师',
        departmentId,
        departmentName: `科室${departmentId}`
      }
    ]
  }
}

// 处理文件变化
const handleFileChange = (file) => {
  // 这里可以处理文件上传前的验证等
}

// 处理文件移除
const handleFileRemove = (file) => {
  const index = fileList.value.indexOf(file)
  if (index !== -1) {
    fileList.value.splice(index, 1)
    // 如果是已保存的文件，也从form.multimedia移除
    if (file.uid) {
      const multimediaIndex = form.multimedia.findIndex(item => item.fileId === file.uid)
      if (multimediaIndex !== -1) {
        form.multimedia.splice(multimediaIndex, 1)
      }
    }
  }
}

// 提交表单
const submitForm = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑模式
          await medicalRecordAPI.updateMedicalRecord(recordId.value, form)
          ElMessage.success('医疗记录更新成功')
        } else {
          // 新增模式
          await medicalRecordAPI.createMedicalRecord(form)
          ElMessage.success('医疗记录创建成功')
        }
        // 返回列表页
        router.push('/medical-records/list')
      } catch (error) {
        console.error('保存医疗记录失败', error)
        ElMessage.error(error.message || '保存失败')
      }
    } else {
      ElMessage.warning('请完善表单信息')
      return false
    }
  })
}

// 取消表单
const cancelForm = () => {
  ElMessageBox.confirm('确认放弃当前编辑内容？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push('/medical-records/list')
  }).catch(() => {})
}

// 页面加载时获取数据
onMounted(async () => {
  console.log('医疗记录表单初始化')
  
  try {
    // 先获取科室列表
    await getDepartments()
    console.log('科室列表:', departmentOptions.value)
    
    // 编辑模式下获取详情
    if (isEdit.value) {
      await getRecordDetail()
    } else {
      // 新增模式，可以初始化一些默认值
      form.diagnosis = [{ type: '初步诊断', code: '', name: '', description: '' }]
      
      // 如果URL中包含查询参数，可以自动填充相关字段
      if (route.query.patientId) {
        form.patientId = route.query.patientId
        // 获取患者信息
        patientAPI.getPatient(route.query.patientId).then(res => {
          patientOptions.value = [res.data]
        }).catch(error => {
          console.error('获取患者信息失败', error)
        })
      }
      
      // 设置默认科室
      if (route.query.departmentId) {
        form.departmentId = route.query.departmentId
      } else {
        // 如果没有指定科室，默认设置为内科
        form.departmentId = '1'
      }
      
      console.log('初始化时设置科室为:', form.departmentId)
      
      // 直接调用科室变更处理函数，获取对应的医生列表
      // 不使用setTimeout延迟，立即加载医生列表
      await handleDepartmentChange(form.departmentId)
      
      // 如果URL中包含医生ID，设置默认医生
      if (route.query.doctorId) {
        form.doctorId = route.query.doctorId
      }
    }
  } catch (error) {
    console.error('初始化表单数据失败:', error)
    ElMessage.error('加载表单数据失败，请刷新页面重试')
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.patient-option {
  display: flex;
  align-items: center;
}

.patient-id {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.patient-info {
  margin-left: auto;
  color: #909399;
  font-size: 12px;
}

.file-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 